package com.zlop.exception;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.log4j.Log4j2;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.NoHandlerFoundException;

import com.alibaba.fastjson.JSONObject;
import com.zlop.common.dto.Result;

/**
 * 统一异常处理
 *
 * @author  曾令鹏
 * @since   jdk1.8
 * @version 2018年4月8日 曾令鹏
 */
@Log4j2
@ControllerAdvice
public class GlobalDefaultExceptionHandle {

	@ExceptionHandler(Exception.class)
	public String defaultExceptionHandle(HttpServletRequest request, HttpServletResponse response, Exception exception) {
		//请求类型：可以区分对待ajax和普通请求
        String requestType = request.getHeader("X-Requested-With");
        if(StringUtils.isBlank(requestType)){
        	//普通请求
        	log.error(exception.getMessage(), exception);
            return "redirect:/error";
        }
        //ajax请求
        Result result = null;
        if (exception instanceof IllegalArgumentException) {
			result = Result.error(exception.getMessage());
		} else if (exception instanceof NoHandlerFoundException) {
			result = Result.error("接口 [" + request.getRequestURI() + "] 不存在");
		} else {
			result = Result.error("接口 [" + request.getRequestURI() + "] 内部错误，请联系管理员");
			log.error(exception.getMessage(), exception);
		}
        responseResult(result, response);
        return null;
	}
	
	/**
	 * json返回
	 * 
	 * @param result
	 * @param response
	 */
	private void responseResult(Result result, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		try {
			PrintWriter writer = response.getWriter();
			writer.write(JSONObject.toJSONString(result));
			writer.flush();
			writer.close();
		} catch (IOException e) {
			log.error(e.getMessage());
		}
	}
	
	
}
